/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package FileManager;

/**
 *
 * @author DucThien
 */
import java.awt.Color;
import java.net.*;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.filechooser.FileSystemView;
import javax.swing.table.DefaultTableModel;

public class FileTransfer_SERVER {

    public static void ReceiveFile(String path , String fileName , Socket socket) throws InterruptedException{
        ByteArrayOutputStream arrayOutput = new ByteArrayOutputStream(); 
        InputStream inuputSt = null; 
        int processedByte; 
        byte[] theByte = new byte[1];
        try {
            inuputSt = socket.getInputStream();
        } catch (IOException ex) {
            Logger.getLogger(FileTransfer_SERVER.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (inuputSt != null) { 

            FileOutputStream fileOutput = null; 
            BufferedOutputStream bufferedOutput = null; 
            try { 
                System.out.println("downloading target file...");
                Thread.sleep(800);
                fileOutput = new FileOutputStream(path+fileName); 
                bufferedOutput = new BufferedOutputStream(fileOutput); 
                processedByte = inuputSt.read(theByte, 0, theByte.length); 

                do { 
                        arrayOutput.write(theByte); 
                        processedByte = inuputSt.read(theByte); 
                } while (processedByte != -1); 

                bufferedOutput.write(arrayOutput.toByteArray()); 
                bufferedOutput.flush(); 
                bufferedOutput.close(); 
                System.out.println("file downloaded");
                //socket.close(); 
            } catch (IOException ex) { 
                System.out.println("file transfer error."); 
            } 
        }
    }
    public static void SendFile(String path , Socket socket){
            BufferedOutputStream bufferedOutput = null; 

            try { 
                bufferedOutput = new BufferedOutputStream(socket.getOutputStream()); 
            } catch (IOException ex) { 
                // Do exception handling 
            } 

            if (bufferedOutput != null) { 
                File fileToSend = new File(path); 
                byte[] mybytearray = new byte[(int) fileToSend.length()]; 

                FileInputStream fileInputSt = null; 

                try { 
                    fileInputSt = new FileInputStream(fileToSend); 
                } catch (FileNotFoundException ex) { 
                    // exception stuff
                } 
                BufferedInputStream bufferedInput = new BufferedInputStream(fileInputSt); 

                try { 
                    bufferedInput.read(mybytearray, 0, mybytearray.length); 
                    bufferedOutput.write(mybytearray, 0, mybytearray.length); 
                    bufferedOutput.flush(); 
                    bufferedOutput.close(); 
                    //connection.close(); 

                    //file1.txt has been downloaded
                    return; 
                } catch (IOException ex) { 
                    System.out.println("can not send file from server !!! ");
                    
                } 
            } 
    }
    
    public Vector<folderTree> getListFolderAndFiles(String fromPath){
        Vector<folderTree> list = new Vector<>();
        if(".".equals(fromPath)){
            File[] listRoot = File.listRoots();
            for(int i = 0 ; i < listRoot.length ; i++){
                if(listRoot[i].isHidden())
                    list.add(new folderTree(listRoot[i].getAbsolutePath(), listRoot[i].getAbsolutePath() , "hard_disk","Partition")); 
            }
        }else{
            File f = new File(fromPath);
            File[] listFolder = f.listFiles();
            for(int i = 0 ; i < listFolder.length ; i++){
                if(!listFolder[i].isHidden()){
                    if(listFolder[i].isDirectory()){
                         list.add(new folderTree(listFolder[i].getName(), listFolder[i].getAbsolutePath(), "folder","Folder")); 
                    }else{
                         list.add(new folderTree(listFolder[i].getName(), listFolder[i].getAbsolutePath(), "file" ,String.valueOf(listFolder[i].getTotalSpace())));  
                    }
                }
                
            }
        }
       
        return list;
    } 
    
    public void viewList(JTable listView , Vector<folderTree> list){
        Map<Object, Icon> icons = new HashMap<Object, Icon>();
        Vector<Vector<String>> listData = new Vector<>(list.size());
        for(int i=0 ; i<list.size() ; i++){
            try {
                String typeObject = list.get(i).getType();
                Vector<String> eachRow = new Vector<>();
                eachRow.add(list.get(i).getName());
                eachRow.add(list.get(i).getFile_size());
                listData.add(eachRow);
                switch (typeObject){
                    case "hard_disk":
                        icons.put(list.get(i).getName(),new ImageIcon(this.getClass().getResource("/images/hdd.png")));
                        break;
                    case "folder":
                        icons.put(list.get(i).getName(),new ImageIcon(this.getClass().getResource("/images/folder.png")));
                        break;
                    case "file":
                        String[] fileName = list.get(i).getName().split("\\.");                     
                        File file = File.createTempFile("icon", "."+fileName[1]); 
                        FileSystemView view = FileSystemView.getFileSystemView(); 
                        Icon icon = view.getSystemIcon(file); 
                        icons.put(list.get(i),icon);
                        file.delete();                      
                        break;
                }          
            } catch (IOException ex) {
               ex.printStackTrace();
            }
        }
        Vector<String> header = new Vector<>();
        header.add("Name");
        header.add("Size");
        DefaultTableModel dm = new DefaultTableModel(listData, header);
        listView.setShowGrid(false); 
        listView.setBackground(Color.white);
        listView.setSelectionMode(1); 
        listView.setSelectionBackground(Color.GRAY); 
        listView.setSelectionForeground(Color.WHITE);
        listView.setModel(dm); 
        listView.getColumnModel().getColumn(0).setCellRenderer(new IconListRenderer(icons));
        listView.setColumnSelectionAllowed(true);
        listView.setCellSelectionEnabled(true); 
    } 
}
